package com.goodfox.web.generic.authority.manager;

import java.util.Collection;
import java.util.Date;
import java.util.Iterator;

import org.apache.log4j.Logger;
import org.springframework.aop.framework.ReflectiveMethodInvocation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.AccessDecisionManager;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.authentication.InsufficientAuthenticationException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;

import com.goodfox.web.generic.account.entity.Account;
import com.goodfox.web.generic.account.mapper.AccountMapper;
import com.goodfox.web.generic.log.entity.OperatorLog;
import com.goodfox.web.generic.log.mapper.OperatorLogMapper;

/**
 * 重写决策管理器
 * @author qin gt
 *
 */
public class AccessDecisionManagerImpl implements AccessDecisionManager {

	/** 日志器 */
	private Logger logger=Logger.getLogger(AccessDecisionManagerImpl.class);
	
	/**
	 * 判断角色是否有访问资源的权限
	 */
	@Override
	public void decide(Authentication authentication, Object object, Collection<ConfigAttribute> configAttributes) throws AccessDeniedException,InsufficientAuthenticationException {
		//URL级访问控制
		if(configAttributes == null) {  
            return;  
        }  
        Iterator<ConfigAttribute> iterator = configAttributes.iterator();  
        while(iterator.hasNext()) {  
            ConfigAttribute configAttribute = iterator.next();  
            String needPermission = configAttribute.getAttribute();  
            logger.debug("需要角色：" + needPermission);  
            for(GrantedAuthority ga : authentication.getAuthorities()) { 
            	logger.debug("拥有角色："+ga.getAuthority());
                if(needPermission.equals(ga.getAuthority())) {  
                    return;  
                }  
            }  
        }  
        logger.debug("没有权限访问！");
        throw new AccessDeniedException(" 没有权限访问！ ");
	}

	@Override
	public boolean supports(Class<?> arg0) {
		return true;
	}

	@Override
	public boolean supports(ConfigAttribute arg0) {
		return true;
	}
	
}
